<template>
  <div>
    <!-- 面包屑导航栏 -->
    <BreadCrumb></BreadCrumb>
    <!-- 内容主体部分 -->
    <el-card class="box-card">
      <!-- 搜索框 -->
      <el-row :gutter="20">
        <el-col :span="9">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear='getUserList'>
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户 -->
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible=true">新增用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户表格 -->
      <el-table :data="userList" stripe border>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch v-model="scope.row.mg_state" @change="userStatusChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button type="primary" icon="el-icon-edit" size='mini' @click='editUserDialog(scope.row.id)'></el-button>
            <!-- 删除 -->
            <el-button type="danger" icon="el-icon-delete" size='mini' @click="deleteUser(scope.row.id)"></el-button>
            <!-- 分配角色 -->
            <el-tooltip class="item" effect="dark" content="Top Center 提示文字" placement="top" :enterable='false'>
              <el-button type="warning" icon="el-icon-setting" size='mini'></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog title="新增用户" :visible.sync="dialogVisible" width="40%" @close="addDialogClose">
      <!-- 内容主体部分 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 退出按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
      <!-- 内容主题表单 -->
      <el-form :model="editUser" :rules="editUserRules" ref="editUserRef" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="editUser.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUser.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop='mobile'>
          <el-input v-model="editUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo(editUser.id)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import BreadCrumb from "../common/BreadCrumb.vue";
export default {
  components: {
    BreadCrumb
  },
  data() {
    //校验邮箱
    var chekEmail = (rule, value, cb) => {
      const regEmail =
        /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入正确的邮箱'))
    }

    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) return cb()
      cb(new Error('请输入正确的手机号'))
    }

    return {
      queryInfo: {
        query: '',
        //当前页码值
        pagenum: 1,
        //每页的展示的数据量
        pagesize: 2
      },
      // 所有用户数据
      userList: [],
      total: 4,
      loading: true,
      //添加用户对话框是否出现
      dialogVisible: false,
      // 添加用户表单
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      //添加用户校验规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator: chekEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机电话不能为空', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      //修改用户校验规则
      editUserRules: {
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator: chekEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机电话不能为空', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },

      //编辑用户对话框
      editDialogVisible: false,
      //暂存编辑用户信息
      editUser: {}
    }
  },
  methods: {
    //得到所有用户表单数据
    getUserList() {
      this.$http.get('users', { params: this.queryInfo }).then(res => {
        if (res.data.meta.status !== 200) return this.$message.error(this.data.meta.msg)
        this.total = res.data.data.total
        this.userList = res.data.data.users
        console.log(this.userList);
      })
    },
    //监听表单页码改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    //监听表单当前所在页
    handleCurrentChange(newpage) {
      this.queryInfo.pagenum = newpage
      this.getUserList()
    },
    //修改用户状态
    userStatusChange(info) {
      this.$http.put(`users/${info.id}/state/${info.mg_state}`).then(res => {
        if (res.data.meta.status !== 200) {
          info.mg_state = !info.mg_state
          return this.$message.error('状态跟新失败')
        }
        this.$message.success('状态跟新成功')
      })
    },
    //监听对话框的关闭
    addDialogClose() { //关闭对话框的时候重置表单内容
      this.$refs.addFormRef.resetFields()
    },
    //添加用户
    addUser() {
      //表单预校验
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return
        this.$http.post('users', this.addForm).then(res => {
          if (res.data.meta.status !== 201) return this.$message.error('添加失败')
          //添加成功
          //1.隐藏添加用户的对话框
          this.dialogVisible = false
          //2.重新刷新列表
          this.getUserList()

        })
      })
    },
    //修改用户得到所在行的用户数据
    editUserDialog(id) {
      this.editDialogVisible = true
      //查询该id的用户
      this.$http.get('users/' + id).then(res => {
        console.log(res);
        if (res.data.meta.status !== 200) return this.$message.error('修改失败')
        this.editUser = res.data.data
      })
    },
    //监听修改对话框的关闭
    editDialogClose() {
      this.$refs.editUserRef.resetFields()//重置表单
    },
    //在对话框中编辑用户信息
    editUserInfo(id) {
      console.log(id);
      //实现对话框的表单预验证
      this.$refs.editUserRef.validate(valid => {
        if (!valid) return
        this.$http.put('users/' + id, this.editUser).then(res => {
          if (res.data.meta.status !== 200) return this.$message.error('跟新失败')
          this.$message.success('跟新成功')
          //关闭窗口
          this.editDialogVisible = false
          //重新加载数据
          this.getUserList()
        })
      })
    },
    //删除用户
    deleteUser(id) {
      console.log(id);
      //确认用户是否删除,防止误点
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
        .then(res => {
          console.log(res);
          if (res == 'cancel')
            return this.$message.error('成功取消')
          //用户确定删除
          this.$http.delete('users/' + id).then(res => {
            console.log(res);
            if (res.data.meta.status !== 200)
              return this.$message.error('删除失败')
            //删除成功
            this.$message.success('删除成功')
            //重新渲染表单数据
            this.getUserList()
          })
        })
    }
  },
  created() {
    this.getUserList()
  }
}
</script>

<style>
</style>